﻿
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WinFormsAppCV
{
    public partial class MainForm : Form
    {
        public readonly static Queue<Rectangle> Queue = new();

        readonly Action<string> logAction;
        readonly EmguCVImageMatcher emguCVImageMatcher;

        public MainForm()
        {
            InitializeComponent();

            logAction = new Action<string>(txt =>
            {
                if (listViewTxt.Items.Count > 200)
                {
                    listViewTxt.Items.Clear();
                }
                listViewTxt.Items.Add(txt);
                listViewTxt.SelectedIndex = listViewTxt.Items.Count - 1;

            });

            emguCVImageMatcher = new(txt =>
            {
                //显示日志
                Invoke(logAction, txt);
            });
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            _ = Task.Run(async () =>
            {
                while (true)
                {
                    if (Queue.TryDequeue(out Rectangle result))
                    {
                        Invoke(new Action<Rectangle>(rectangle =>
                        {
                            // 显示绿框并等待用户可见
                            using var overlay = new OverlayForm(rectangle);
                            overlay.Show();
                            Application.DoEvents();  // 强制立即渲染
                            Thread.Sleep(700);

                        }), result);
                    }
                    else
                    {
                        await Task.Delay(100);
                    }
                }
            });
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //while (true) 
            //{
                emguCVImageMatcher.MatchImg(@"res/query.png").MouseLeftClick();
            //}
        }
    }

    /// <summary>
    /// 自定义透明窗体用于绘制绿框
    /// </summary>
    public class OverlayForm : Form
    {
        private readonly Rectangle _targetRect;

        public OverlayForm(Rectangle targetRect)
        {
            _targetRect = targetRect;
            InitializeForm();
        }

        private void InitializeForm()
        {
            FormBorderStyle = FormBorderStyle.None;
            ShowInTaskbar = false;
            TopMost = true;
            BackColor = Color.Magenta;  // 特殊背景色用于透明
            TransparencyKey = Color.Magenta;
            StartPosition = FormStartPosition.Manual;
            Bounds = Screen.PrimaryScreen!.Bounds;
            DoubleBuffered = true;  // 防止闪烁
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            using var pen = new Pen(Color.Lime, 3);  // 绿色边框，线宽3像素
            e.Graphics.DrawRectangle(pen, _targetRect);
        }
    }
}
